#!/bin/bash
# 用法: ./ry.sh {start|stop|restart|status}
# start   启动
# stop    停止
# restart 重启
# status  查看运行状态

#######################################
#               参数定义
#######################################
AppName="smart-admin.jar"

# 统一的 GC 日志配置：适用于 JDK 9+（含 21）
# -Xlog:gc*,gc+heap=debug:logs/gc.log:time,uptimemillis,level,tags
#   - 将 GC 相关日志输出到 logs/gc.log
#   - 显示时间(time)、运行毫秒数(uptimemillis)、日志级别(level) 和标签(tags)
# 其他参数 (MetaspaceSize / MaxMetaspaceSize / SurvivorRatio等) 视你的需求可做调整
JVM_OPTS="-Dname=$AppName \
          -Duser.timezone=Asia/Shanghai \
          -Xms512m \
          -Xmx1024m \
          -XX:MetaspaceSize=128m \
          -XX:MaxMetaspaceSize=512m \
          -XX:+HeapDumpOnOutOfMemoryError \
          -Xlog:gc*,gc+heap=debug:logs/gc.log:time,uptimemillis,level,tags \
          -XX:NewRatio=1 \
          -XX:SurvivorRatio=30 \
          -XX:+UseParallelGC"

APP_HOME=$(pwd)
LOG_PATH="$APP_HOME/logs/$AppName.log"

#######################################
#            函数定义
#######################################

# 启动
function start() {
    # 查找进程ID
    PID=$(ps -ef | grep java | grep "$AppName" | grep -v grep | awk '{print $2}')
    if [ -n "$PID" ]; then
        echo "$AppName is running... (PID: $PID)"
    else
        # 确保logs目录存在
        [ -d "$APP_HOME/logs" ] || mkdir -p "$APP_HOME/logs"
        
        # 以 nohup 方式后台启动，将输出重定向到 LOG_PATH
        nohup java $JVM_OPTS -jar "$AppName" > "$LOG_PATH" 2>&1 &
        echo "Start $AppName success..."
    fi
}

# 停止
function stop() {
    echo "Stop $AppName"
    PID=""
    
    # 内部函数：查询PID
    function query() {
        PID=$(ps -ef | grep java | grep "$AppName" | grep -v grep | awk '{print $2}')
    }

    query
    if [ -n "$PID" ]; then
        kill -TERM "$PID"
        echo "$AppName (pid:$PID) exiting..."
        
        # 等待进程退出
        while [ -n "$PID" ]
        do
            sleep 1
            query
        done
        echo "$AppName exited."
    else
        echo "$AppName already stopped."
    fi
}

# 重启
function restart() {
    stop
    sleep 2
    start
}

# 查看状态
function status() {
    PID_COUNT=$(ps -ef | grep java | grep "$AppName" | grep -v grep | wc -l)
    if [ "$PID_COUNT" -ne 0 ]; then
        echo "$AppName is running..."
    else
        echo "$AppName is not running..."
    fi
}

#######################################
#           主流程：解析命令
#######################################

if [ -z "$1" ]; then
    echo -e "\033[0;31m未输入操作名\033[0m \033[0;34m{start|stop|restart|status}\033[0m"
    exit 1
fi

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        restart
    ;;
    status)
        status
    ;;
    *)
        echo "用法: $0 {start|stop|restart|status}"
        exit 1
    ;;
esac

